<template>
	<view class="padding w-full">
		<use-navbar ref="navbar" title=" " :show="true" left-icon="icontubiaozhizuomoban-11 fs-xxl" bg-color="rgba(255,255,255, 0)"></use-navbar>
		<swiper vertical circular previous-margin="40px" next-margin="40px"  duration="200"
			class="pos-a pos-top" style="width: calc(100vw - 60rpx); height: 100vh;"
			:current="swiperIdx" @change="swiperChange">
			<swiper-item v-for="(item, idx) in noteDatas" :key="idx">
				<view class="wh-full bg-main border-radius animated-all" :style="{ 'transform': `scale(${swiperIdx == idx ? 1 : 0.95})` }">
					<!-- <scroll-view scroll-y scroll-anchoring scroll-with-animation class="h-full"> -->
					<!-- 01. 轮播区 -->
					<view class="swiper-area w-full">
						<swiper class="h-full" indicator-dots circular="true" duration="400" :current="subSwiperIdx" @change="subSwiperChange">
							<swiper-item v-if="item.note_video && item.note_video.url" class="dflex-c">
								<view class="wh-full pos-r dflex-c" style="background: #000;" @click="toVideo(item)">
									<!-- #ifdef APP -->
									<!-- 显示视频封面 -->
									<image :src="item.note_video.poster" class="wh-full" lazy-load mode="aspectFill"></image>
									
									<!-- 播放图标 -->
									<view v-if="item.note_video.pause" class="iconfont iconbofang pos-a pos-tl-c ft-white fs-90"></view>
									<!-- #endif -->
									
									<!-- #ifdef H5 || MP-WEIXIN -->
									<!-- v-show="init && !showVideoPoster" -->
									<video 
										v-if="[data.__idx-1, data.__idx, data.__idx+1].includes(item.__idx)"
										:id="'uVideo' + item.__idx"
										:src="item.note_video.url" 
										:poster="item.note_video.poster" 
										:poster-for-crawler="item.note_video.poster"
										:show-fullscreen-btn="false"
										:loop="true"
										:controls="item.note_video.pause"
										:show-play-btn="false"
										:show-center-play-btn="false"
										:enable-progress-gesture="false"
										@ended="item.note_video.pause = true"
										@loadedmetadata="videoLoaded"
										object-fit="contain"
										:class="[item.note_video.width > item.note_video.height ? 'w-full' : 'h-full']"
										></video>
									
									<!-- 显示视频封面 -->
									<image v-else :src="item.note_video.poster" class="wh-full" lazy-load mode="aspectFill"></image>
									
									<!-- 播放图标 -->
									<view v-if="item.note_video.pause" class="iconfont iconbofang pos-a pos-tl-c ft-white fs-90"></view>
									<!-- #endif -->
								</view>
							</swiper-item>
							<swiper-item v-for="(imgObj, imgIdx) in item.note_imgs" :key="imgIdx">
								<view class="wh-full dflex-c">
									<image :src="imgObj.url" class="wh-full" lazy-load mode="widthFix"
										@click.stop="preview(item.note_imgs, imgObj.url)"></image>
								</view>
							</swiper-item>
						</swiper>
					</view>
					
					<!-- 02. 数据区 -->
					<view class="data-area bg-main padding">
						<view class="dflex-b margin-tb-sm">
							<view class="dflex" @click.stop="toUser(item)">
								<image :src="item.create_uheadimg || '/static/images/user/default.png'" 
									class="headimg border-radius-c"
									style="width: 80rpx; height: 80rpx;"></image>
								<view class="margin-left-xs fs-xs">{{ item.create_uname }}</view>
							</view>
							<view v-show="isload && item.create_uid != member._id" class="bg-drak border-radius-lg padding-lr fs-xs dflex-c" @click="toFollow(item)">
								<text class="iconfont" :class="[ item.follow ? 'iconaixin-01 ft-base' : 'iconaixin' ]"></text>
								<text class="padding-tb-16" style="margin-left: 6rpx;">{{ item.follow ? '已关注' : '加关注' }}</text>
							</view>
						</view>
						<view @click.stop="toMore(item)">
							<view class="dflex-b margin-bottom-xs">
								<text class="title flex1 fwbd clamp fs">{{ item.note_title }}</text>
								<text class="iconfont iconjiantou-01 ft-dark fs-sm"></text>
							</view>
							<text class="clamp-2">{{ item.note_desc }}</text>
						</view>
					</view>
					<!-- 03. 操作区 -->
					<view v-if="isload" class="oper-area pos-f dflex-b w-full padding-lr-lg">
						<view class="dflex">
							<view class="btn-area dflex-c" :class="{ active: item.likes }" @click="toLikes(item)">
								<view class="iconfont animated" :class="[ item.likes ? 'iconaixin-01' : 'iconaixin', islikes ? 'scale' : '' ]"></view>
								<text>{{ item.note_praise || 0 }}</text>
							</view>
							<view class="btn-area dflex-c" :class="{ active: item.collect }" @click="toCollect(item)">
								<view class="iconfont animated" style="animation-duration: 1.75s;" :class="[ item.collect ? 'iconshoucang-' : 'iconshoucang-01', iscollect ? 'rotate' : '' ]"></view>
								<text>{{ item.note_collect || 0 }}</text>
							</view>
						</view>
						<view class="dflex">
							<!-- #ifdef MP-WEIXIN -->
							<button class="btn no-border padding-0" open-type="share">
								<view class="dflex-c border-radius-c margin-right"
									style="background: #fff; width: 76rpx; height: 76rpx;"
									@click="toShare(item)">
									<view class="iconfont iconfenxiang ft-base fwbd fs-xl"></view>
								</view>
							</button>
							<!-- #endif -->
							<view v-if="item && item.note_gid" class="btn-container border-radius-big">
								<view class="tac padding-tb-sm flex1 bg-base" style="padding: 16rpx 50rpx;" @click="toBuy(item)">购买同款</view>
							</view>
						</view>
					</view>
					
					<view class="w-full" style="height: 100rpx;"></view>
					<!-- </scroll-view> -->
				</view>
			</swiper-item>
		</swiper>
		
		<use-popup mode="bottom" bgclass=" " :close-icon="true" v-model="moreShow">
			<view class="bg-main padding border-radius-top30 safe-area-inset-bottom"
				style="min-height: 50vh;">
				<view class="dflex-c margin-top-lg margin-bottom">
					<text class="fwbd fs-lg">{{ data.note_title }}</text>
				</view>
				<scroll-view class="overflow-auto" style="max-height: 40vh;" scroll-y>
					<view class="margin-top-xs">
						<text>{{ data.note_desc }}</text>
					</view>
				</scroll-view>
			</view>
		</use-popup>
		
		<use-video v-model="videoShow" :videoObj="videoObj" @exit="videoShow = false;"></use-video>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	export default {
		computed: {
			...mapState(['islogin', 'member'])
		},
		data() {
			return {
				id: '',
				data: {},
				noteDatas: [],
				init: false,
				isload: false,
				uVideo: null,
				swiperIdx: 0,
				subSwiperIdx: 0,
				islikes: false,
				iscollect: false,
				isfollow: false,
				moreShow: false,
				iswifi: false,
				
				videoShow: false,
				videoObj: {}
			};
		},
		onLoad(res) {
			if (res && res.id) {
				this.id = res.id;
			} 
			
			if (!this.id) {
				this.$api.msg('笔记ID无效');
				return;
			}
			
			// 加载数据
			this.loadData();
			
			this.$api.get_env(res => {
				console.log('networkType', res.networkType);
				this.iswifi = res.networkType === 'wifi';
				if (this.iswifi) {
					// this.$api.msg('当前wifi环境，已开启滑页自动播放视频', 2600)
				}
			});
			
			const noteData = uni.getStorageSync('__shopping_detail_data');
			if (noteData && noteData._id == this.id) {
				// noteData._id = '';
				this.setData({ note: noteData });
			}
			
			uni.getStorage({
				key: '__shopping_detail_datas',
				success: (res) => {
					console.log('__shopping_detail_datas res', res);
					this.setDatas(res.data);
				}
			});
			
		},
		onShow() {
			uni.hideLoading();
		},
		onPageScroll(res) {
			
		},
		onReachBottom(res) {
			console.log('onReachBottom', res);
		},
		onShareAppMessage: function(ops) {
			let mid = 0;
			if (this.member && this.member._id) {
				mid = this.member._id;
			}

			return {
				title: this.data.note_title || this.$config.appslogan || '用云 · 让开发更简单',
				path: `/sub-shopping/pages/detail?id=${this.id}&mid=${mid}`, //这里设定都是以"/page"开头,并拼接好传递的参数
				success: function(res) {
					// 转发成功
					console.log('转发成功', res);
				},
				fail: function(res) {
					// 转发失败
					console.log('转发失败', res);
				}
			};
		},
		methods: {
			loadData() {
				this.$func.usemall.call('shopping/detail', { id: this.id }).then(res => {
					console.log('note-detail', res);
					this.isload = true;
					if (res.code == 200) {
						this.setData({ note: res.datas });
						return;
					}
				});
			},
			setData(res) {
				if (this.data && this.data._id) return;
				
				if (res.note && res.note.note_video) {
					res.note.note_video.pause = true;
					
					if (this.init) {
						res.note.__idx = this.data.__idx;
						res.note.note_video.pause = this.data.note_video.pause;
					}
					
					this.init = true;
				}
				
				this.data = res.note;
				let idx = this.noteDatas.findIndex(x => x.__idx == this.data.__idx);
				if (idx !== -1) {
					this.noteDatas[idx] = this.data;
				} else {
					this.noteDatas.push(this.data);
				}
				
				if (this.data._id && this.data.note_video) {
					// #ifndef APP
					this.toVideo(this.data);
					// #endif
				}
			},
			setDatas(res) {
				console.log('setDatas res', res.filter(x => !x.isad), res.filter(x => x.isad));
				res = res.filter(x => !x.isad);
				
				res.sort((v1, v2) => {
					if (v1.__idx > v2.__idx) {
						return 1;
					}
					return -1;
				});
				res.forEach((note, idx) => {
					if (note && note.note_video) {
						note.note_video.pause = true;
					}
				});
				
				const idx = res.findIndex(x => x._id == this.data._id);
				
				if (idx > 0) {
					this.noteDatas = [...this.noteDatas, ...res.slice(idx + 1, res.length), ...res.slice(0, idx)];
					return;
				}
				
				this.noteDatas = [...this.noteDatas, ...res.slice(idx + 1, res.length)];
			},
			swiperChange(res) {
				if (res.detail) {
					this.swiperIdx = res.detail.current;
					if (this.uVideo) {
						this.uVideo.pause();
						this.data.note_video.pause = true;
					}
					
					this.data = this.noteDatas[this.swiperIdx];
					this.uVideo = null;
					
					// todo 判断当前网络环境，wifi下开启自动播放视频功能
					// #ifndef APP
					this.toVideo(this.data);
					// #endif
				}
			},
			// 内 swiper
			subSwiperChange(res) {
				if (res.detail && res.detail.current !== 0 && this.uVideo) {
					this.uVideo.pause();
					this.data.note_video.pause = true;
				}
			},
			// 点赞|取消点赞
			toLikes(item) {
				if (!this.islogin) {
					this.$api.tologin()
					return;
				}
				
				if (this.islikes) return;
				this.islikes = true;
				
				console.log('toLikes', item);
				let url = 'shopping/likes';
				
				if (item.likes) {
					url = 'shopping/likesCancel';
					item.note_praise--;
					if (item.note_praise < 0) item.note_praise = 0;
				} else {
					item.note_praise++;
				}
				
				item.likes = !item.likes;
				this.$func.usemall.call(url, { id: item._id }).then(res => {
					console.log('toLikes', url, res);
					this.islikes = false;
					if (res.code == 200) {
						// 操作成功
						// 点赞操作，数据同步
						uni.$emit('__shopping_likes', { note: item, likes: item.likes });
						return;
					}
					
					this.$api.msg(res.msg);
					item.likes = !item.likes;
					if (item.likes) {
						item.note_praise++;
					} else {
						item.note_praise--;
						if (item.note_praise < 0) item.note_praise = 0;
					}
				})
			},
			// 收藏|取消收藏
			toCollect(item) {
				if (!this.islogin) {
					this.$api.tologin()
					return;
				}
				
				if (this.iscollect) return;
				this.iscollect = true;
				
				console.log('toCollect', item);
				let url = 'shopping/collect';
				if (item.collect) {
					url = 'shopping/collectCancel';
				}
				
				this.$func.usemall.call(url, { id: item._id }).then(res => {
					console.log('toCollect', url, res);
					
					this.iscollect = false;
					if (res.code == 200) {
						item.collect = res.datas.collect;
						// 收藏操作，数据同步
						uni.$emit('__shopping_collect', { note: item, collect: item.collect });
						if (item.collect) {
							this.$api.msg('收藏成功');
							item.note_collect++;
						} else {
							item.note_collect--;
							if (item.note_collect < 0) item.note_collect = 0;
						}
						return;
					}
					
					this.$api.msg(res.msg);
				})
			},
			// 立即购买
			toBuy(item) {
				// 跳转商品详情
				this.$api.togoods({
					id: item.note_gid
				});
			},
			// 个人中心
			toUser(item) {
				uni.navigateTo({
					url: '/sub-shopping/pages/user?id=' + item.create_uid
				})
			},
			// 关注|取消关注
			toFollow(item) {
				if (!this.islogin) {
					this.$api.tologin()
					return;
				}
				
				if (this.isfollow) return;
				this.isfollow = true;
				uni.showLoading({
					title: '请求中'
				});
				
				let url = 'shopping/follow';
				this.$func.usemall.call(url, { id: item.create_uid }).then(res => {
					console.log('toFollow', url, res);
					
					uni.hideLoading();
					this.isfollow = false;
					if (res.code == 200) {
						item.follow = res.datas.follow;
						
						// 同步更新笔记作者的关注状态
						this.noteDatas.forEach((note, idx) => {
							if (note.create_uid === item.create_uid) {
								note.follow = item.follow;
							}
						})
						return;
					}
					
					this.$api.msg(res.msg);
				})
			},
			toShare() {
				
			},
			// 创建video context
			toVideo(res) {
				// #ifdef APP
				this.data = res;
				this.videoObj = this.data.note_video;
				this.videoShow = true;
				return;
				// #endif
				
				if (this.data.__idx !== res.__idx || !this.uVideo) {
					this.data = res;
					this.uVideo = uni.createVideoContext('uVideo' + res.__idx, this);
					console.log('videoObj', this.uVideo);
				}
				
				if (!this.data.note_video.pause) {
					// 暂停
					this.uVideo.pause();
					this.data.note_video.pause = true;
					return;
				}
				
				// 播放
				this.uVideo.play();
				this.data.note_video.pause = false;
			},
			videoLoaded(res) {
				console.log('videoLoaded', res);
			},
			// 图片预览
			preview(imgs, cur) {
				console.log('preview', imgs, cur);
				uni.previewImage({
					urls: imgs.map(x => x.url),
					current: cur,
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success: function(data) {
							console.log(res);
						},
						fail: function(err) {
							console.log(err);
						}
					}
				});
			},
			toMore(res) {
				this.data = res;
				this.moreShow = true;
			}
		}
	};
</script>

<style lang="scss">
	page {
		background: rgba(255, 106, 108, .9);
		width: 100vw;
		height: 100vh;
	}

	.swiper-area {
		height: calc(100% - 400rpx);
	}
	
	.data-area {
		height: 400rpx;
	}
	.title {
		color: $font-color-dark;
		height: 46rpx;
		line-height: 46rpx;
	}
	
	.oper-area {
		left: 0;
		bottom: 0;
		background: rgba(245, 245, 245, 0.95);
		box-shadow: 0 0 20rpx 0 #f0f0f0;
		height: 100rpx;
		z-index: 95;
		border-bottom-left-radius: 30rpx;
		border-bottom-right-radius: 30rpx;

		.btn-area {
			color: #000;
			width: 96rpx;
			margin-right: 30rpx;
			text-align: center;

			.iconfont {
				font-size: 40rpx;
				line-height: 48rpx;
				margin-right: 6rpx;
			}
		}
	}
</style>
